<template>
  <div class="employee-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="员工姓名">
        <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable />
      </el-form-item>
      <el-form-item label="所属公司">
        <el-select v-model="searchForm.companyId" placeholder="请选择公司" clearable>
          <el-option
            v-for="item in companyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门">
        <el-input v-model="searchForm.department" placeholder="请输入部门" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">添加员工</el-button>
      <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">批量删除</el-button>
      <el-button @click="fetchEmployeeList" :loading="loading">刷新</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      row-key="id"
      :header-cell-style="{ background: '#f5f7fa' }"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="scope">
          {{ scope.row.gender === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="company_name" label="所属公司" min-width="150" />
      <el-table-column prop="department" label="部门" width="120" />
      <el-table-column prop="position" label="职位" width="120" />
      <el-table-column prop="phone" label="联系电话" width="150" />
      <el-table-column prop="email" label="电子邮箱" min-width="180" />
      <el-table-column prop="entry_date" label="入职日期" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '在职' : '离职' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="employeeFormRef"
        :model="employeeForm"
        :rules="employeeFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="所属公司" prop="companyId">
          <el-select v-model="employeeForm.companyId" placeholder="请选择公司" style="width: 100%">
            <el-option
              v-for="item in companyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="employeeForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="employeeForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="employeeForm.department" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="employeeForm.position" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="employeeForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="employeeForm.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="入职日期" prop="entryDate">
          <el-date-picker
            v-model="employeeForm.entryDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="employeeForm.status">
            <el-radio :label="1">在职</el-radio>
            <el-radio :label="0">离职</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="employeeForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="员工详情" v-model="viewDialogVisible" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="姓名">{{ employeeDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ employeeDetail.gender === 1 ? '男' : '女' }}</el-descriptions-item>
        <el-descriptions-item label="所属公司">{{ employeeDetail.company_name }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ employeeDetail.department }}</el-descriptions-item>
        <el-descriptions-item label="职位">{{ employeeDetail.position }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ employeeDetail.phone }}</el-descriptions-item>
        <el-descriptions-item label="电子邮箱">{{ employeeDetail.email }}</el-descriptions-item>
        <el-descriptions-item label="入职日期">{{ employeeDetail.entry_date }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="employeeDetail.status === 1 ? 'success' : 'danger'">
            {{ employeeDetail.status === 1 ? '在职' : '离职' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ employeeDetail.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getEmployeeList,
  getEmployeeById,
  createEmployee,
  updateEmployee,
  deleteEmployee,
  getCompanyList
} from '@/api/personnel.js'

// 表格数据相关
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 公司选项
const companyOptions = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  companyId: '',
  department: ''
})

// 员工表单
const employeeFormRef = ref(null)
const employeeForm = reactive({
  id: null,
  companyId: '',
  name: '',
  gender: 1,
  department: '',
  position: '',
  phone: '',
  email: '',
  entryDate: '',
  status: 1,
  remark: ''
})

// 表单验证规则
const employeeFormRules = {
  companyId: [
    { required: true, message: '请选择所属公司', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请输入部门', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  entryDate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 对话框相关
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const employeeDetail = ref({})

const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '添加员工' : '编辑员工'
})

// 获取公司列表
const fetchCompanyOptions = async () => {
  try {
    const res = await getCompanyList({ pageSize: 1000 })
    if (res.data && res.data.data && res.data.data.list) {
      companyOptions.value = (res.data.data.list || []).map(item => ({
        value: item.company_id,
        label: item.company_name
      }))
    } else {
      console.error("公司列表数据结构不符合预期:", res.data)
      ElMessage.error('获取公司列表数据格式错误')
      companyOptions.value = []
    }
  } catch (error) {
    console.error('获取公司列表失败', error)
    ElMessage.error('获取公司列表失败')
  }
}

// 获取员工列表数据
const fetchEmployeeList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.name,
      companyId: searchForm.companyId,
      department: searchForm.department
    }
    
    const res = await getEmployeeList(params)
    
    if (res.data && res.data.data && res.data.data.list) {
      tableData.value = res.data.data.list
      total.value = res.data.data.total || 0
    } else {
      console.error("响应数据结构不符合预期:", res.data)
      tableData.value = []
      total.value = 0
      ElMessage.warning('获取员工列表数据格式不正确')
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchEmployeeList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  fetchEmployeeList()
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchEmployeeList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchEmployeeList()
}

// 表格选择相关
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 添加员工
const handleAdd = () => {
  dialogType.value = 'add'
  resetEmployeeForm()
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  resetEmployeeForm()
  
  try {
    const res = await getEmployeeById(row.id)
    
    if (res.data && res.data.data) {
      const employeeData = res.data.data
      Object.keys(employeeForm).forEach(key => {
        if (key in employeeData) {
          employeeForm[key] = employeeData[key]
        }
      })
      
      // 特殊处理一些字段名不一致的情况
      if (employeeData.company_id) {
        employeeForm.companyId = employeeData.company_id
      }
      if (employeeData.entry_date) {
        employeeForm.entryDate = employeeData.entry_date
      }
    } else {
      ElMessage.error('获取员工详情数据格式错误')
      return
    }
  } catch (error) {
    console.error('获取员工详情失败', error)
    ElMessage.error('获取员工详情失败')
    return
  }
  
  dialogVisible.value = true
}

// 查看员工详情
const handleView = async (row) => {
  try {
    const res = await getEmployeeById(row.id)
    
    if (res.data && res.data.data) {
      employeeDetail.value = res.data.data
    } else {
      ElMessage.error('获取员工详情数据格式错误')
      return
    }
    viewDialogVisible.value = true
  } catch (error) {
    console.error('获取员工详情失败', error)
    ElMessage.error('获取员工详情失败')
  }
}

// 删除员工
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该员工信息吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteEmployee(row.id)
        ElMessage.success('删除成功')
        if (tableData.value.length === 1 && currentPage.value > 1) {
          currentPage.value--
        }
        fetchEmployeeList()
      } catch (error) {
        console.error('删除员工失败', error)
        ElMessage.error('删除员工失败')
      }
    })
    .catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的员工')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 名员工吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      loading.value = true
      try {
        const ids = selectedRows.value.map(item => item.id)
        const promises = ids.map(id => deleteEmployee(id))
        await Promise.all(promises)
        
        ElMessage.success('批量删除成功')
        if (tableData.value.length === selectedRows.value.length && currentPage.value > 1) {
          currentPage.value--
        }
        fetchEmployeeList()
      } catch (error) {
        console.error('批量删除员工失败', error)
        ElMessage.error('批量删除员工失败')
      } finally {
        loading.value = false
      }
    })
    .catch(() => {})
}

// 重置表单
const resetEmployeeForm = () => {
  if (employeeFormRef.value) {
    employeeFormRef.value.resetFields()
  }
  
  Object.assign(employeeForm, {
    id: null,
    companyId: '',
    name: '',
    gender: 1,
    department: '',
    position: '',
    phone: '',
    email: '',
    entryDate: '',
    status: 1,
    remark: ''
  })
}

// 提交表单
const submitForm = () => {
  employeeFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      if (dialogType.value === 'add') {
        await createEmployee(employeeForm)
        ElMessage.success('添加成功')
      } else {
        await updateEmployee(employeeForm.id, employeeForm)
        ElMessage.success('更新成功')
      }
      dialogVisible.value = false
      fetchEmployeeList()
    } catch (error) {
      console.error('保存员工信息失败', error)
      ElMessage.error('保存员工信息失败')
    } finally {
      submitLoading.value = false
    }
  })
}

onMounted(() => {
  fetchCompanyOptions()
  fetchEmployeeList()
})
</script>

<style scoped>
.employee-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin-bottom: 20px;
  padding: 18px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media screen and (max-width: 768px) {
  .search-form :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }
  
  .action-bar {
    flex-direction: column;
    gap: 10px;
  }
  
  .action-bar .el-button {
    width: 100%;
  }
}
</style>
